
function getFieldReady(){
    var params = new Object();
    //databaseId是全局变量 保存当前选中的节点的id
    //同时databaseId和catalogId对于数据包是一致的
    params['databaseId'] = databaseId;
    loadFieldData(params);
    loadInfo(params);
    loadAuth(params);
    $("#database_data").treegrid({
        onClickRow:function(row){
            params['dataSelected'] = row;
        }
    });
    return function () {
        return params;
    }
}

//加载数据库的数据信息
function loadFieldData(params){
    $("#database_data").treegrid({
        url: schemaUrl.fieldLoad+"?did="+params['databaseId']
        }
    )
}
//加载数据库的描述信息
function loadInfo(params){
    $.post(schemaUrl.getSchemaInfo,{id:params['databaseId']},function(result){
        $("#infoPicName").prop('value',result.data[0]);
        $("#info_area").prop('value',result.data[1]);
    });
}
//加载数据库权限用户
function loadAuth(params){
    $("#authDR").combobox({
        url:schemaUrl.loadAuthUsers+'?id='+params['databaseId'],
        valueField:"id",
        textField:"userName",
        onSelect:function(rec){
            //读权限用户
            var readIds = params['readIds'];
            if(readIds){
                readIds.push(rec.id);
            }else{
                readIds = new Array();
                readIds.push(rec.id);
            }
            params['readIds'] = readIds;
        },
        onUnselect:function(rec){
            var readIds = params['readIds'];
            readIds = readIds.filter(function(val){
                return val != rec.id;
            });
            params['readIds'] = readIds;
        }
    });

    $.get(schemaUrl.loadReadUsers+'?schemaId='+params['databaseId'], function(result){
        var pids = eval(result);
        for(var index in pids) {
            var pid = pids[index];
            $("#authDR").combobox('select', pid['id']);
        }
    });

    $("#authDW").combobox({
        url:schemaUrl.loadAuthUsers+'?id='+params['databaseId'],
        valueField:"id",
        textField:"userName",
        onSelect:function(rec){
            //写权限用户
            var writeIds = params['writeIds'];
            if(writeIds){
                writeIds.push(rec.id);
            }else{
                writeIds = new Array();
                writeIds.push(rec.id);
            }
            params['writeIds'] = writeIds;
        },
        onUnselect:function(rec){
            var writeIds = params['writeIds'];
            writeIds = writeIds.filter(function(val){
                return val != rec.id;
            });
            params['writeIds'] = writeIds;
        }
    });

    $.get(schemaUrl.loadWriteUsers+'?schemaId='+params['databaseId'], function(result){
        var pids = eval(result);
        for(var index in pids) {
            var pid = pids[index];
            $("#authDW").combobox('select', pid['id']);
        }
    });
}

function saveAuth(){
    var readData={
        databaseId:params()['databaseId'],
        readIds:JSON.stringify(params()['readIds']),
        writeIds:JSON.stringify(params()['writeIds'])
    };
    $.get(schemaUrl.saveAuthUsers,readData,function(result){
        if(result.successful){
            $.messager.show({title: '操作结果', msg: '操作成功'});
        }else{
            $.messager.show({title: '操作结果', msg:result.message});
        }
    });
}

var operations = {create:0,edit:1,remove:2};
var op;
//数据项操作
function newFieldData(){
    var row = params()['dataSelected'];
    if (row ==undefined){
        alert_choose();
        return;
    }else if(row.attributes == fieldCatalogName.trim() || row.attributes == schemaDatabaseName.trim()) {
        $("#database_data_name").show();
        $("#database_data_type").show();
        $("#float_unit").hide();
        $("#float_trend").hide();
        $("#matrix_title_div").hide();
        $("#matrix_tip").hide();
        $("#3matrix_div").hide();
        $('#databaseData_form').form('clear');
        //默认是选择分类
        $('#dataType').combobox('select', fieldCatalogType);
        $("input[name='float_trend_radio']").eq(0).attr("checked","checked");
        $('#databaseData_dialog').dialog('open').dialog('setTitle', '添加数据项');
        $('#dataType').combobox({
            onChange: function () {
                var val = $("#dataType").combobox('getValue');
                if (val == fieldMatrix) {
                    $("#float_unit").hide();
                    $("#float_trend").hide();
                    $("#3matrix_div").hide();
                    $("#matrix_title_div").show();
                    $("#matrix_tip").show();
                }else if(val==fieldFloat){
                    $("#float_unit").show();
                    $("#float_trend").show();
                    $("#matrix_title_div").hide();
                    $("#matrix_tip").hide();
                    $("#3matrix_div").hide();
                } else if(val==field3Matrix){
                    $("#float_unit").hide();
                    $("#float_trend").hide();
                    $("#matrix_title_div").hide();
                    $("#matrix_tip").hide();
                    $("#3matrix_div").show();
                }else {
                    $("#matrix_title_div").hide();
                    $("#matrix_tip").hide();
                    $("#float_unit").hide();
                    $("#float_trend").hide();
                    $("#3matrix_div").hide();
                }
            }
        });
        op = operations.create;
    }else{
        alert_no_leaf();
        return;
    }
}

function editFieldData(){
    var row=$('#database_data').treegrid('getSelected');
    var remark3="";
    if(!row||row.id==0){
        alert_choose();
        return;
    }else if(row.attributes==fieldMatrixName.trim()){
        $.get(fieldUrl.getRemark3,{id:row.id},function(result){
            if(result.successful){
                remark3=result.data;
                $("#package_data_name").show();
                $("#package_data_type").hide();
                $("#float_unit").hide();
                $("#float_trend").hide();
                $("#3matrix_div").hide();
                $("#matrix_title_div").show();
                $("#matrix_tip").show();
                $("input[name='name']").prop('value',row.text);
                $("#titlearea").prop('value',remark3);
                $('#databaseData_dialog').dialog('open').dialog('setTitle','修改数据项');
            }
        });
    }else if(row.attributes==fieldFloatName.trim()){
        var remark1=1;
        $.get(fieldUrl.getRemark1,{id:row.id},function(result){
            if(result.successful){
                remark1=result.data;
            }
        });
        $.get(fieldUrl.getRemark3,{id:row.id},function(result){
            if(result.successful){
                remark3 = result.data;
                $("#database_data_name").show();
                $("#database_data_type").hide();
                $("#matrix_title_div").hide();
                $("#3matrix_div").hide();
                $("#matrix_tip").hide();
                $("#float_unit").show();
                $("#float_trend").show();
                $("input[name='name']").prop('value', row.text);
                $("#float_unit_input").prop('value', remark3);
                if(remark1==1){
                    $("#trendRadio1").attr("checked","checked");
                    $("#trendRadio2").removeAttr("checked");
                }else{
                    $("#trendRadio2").attr("checked","checked");
                    $("#trendRadio1").removeAttr("checked");
                }
                $("#float_trend_radio").prop('value', remark1);
                $('#databaseData_dialog').dialog('open').dialog('setTitle', '修改数据项');
            }
        });
    }else if(row.attributes==fieldMatrixName.trim()){
        $.get(fieldUrl.get3MatrixInfo,{id:row.id},function(result){
            if(result.successful){
                remark3=result.data;
                $("#package_data_name").show();
                $("#package_data_type").hide();
                $("#float_unit").hide();
                $("#float_trend").hide();
                $("#3matrix_div").hide();
                $("#matrix_title_div").show();
                $("#matrix_tip").show();
                $("input[name='name']").prop('value',row.text);
                $("#titlearea").prop('value',remark3);
                $('#databaseData_dialog').dialog('open').dialog('setTitle','修改数据项');
            }
        });
    }else{
        $("#database_data_name").show();
        $("#database_data_type").hide();
        $("#matrix_title_div").hide();
        $("#matrix_tip").hide();
        $("#float_unit").hide();
        $("#float_trend").hide();
        $("input[name='name']").prop('value',row.text);
        $('#databaseData_dialog').dialog('open').dialog('setTitle','修改数据项');
    }
    op = operations.edit;
}

function deleteFieldData(){
    var node=$('#database_data').treegrid('getSelected');
    if(!node){
        alert_choose();
        return;
    }
    if(node.id==fieldRootId){
        alert_no_leaf();
        return;
    }
    $.messager.confirm('Confirm', "\""+fieldDeleteTips+"\"", function (n) {
        if (n) {
            op = operations.remove;
            dataOperator.remove();
        }
    });
}

function saveFieldData(){
    var row = params()['dataSelected'];
    var name = $("#databaseData_form input[name='name']").val();
    var type = params()['selectedRecordType'];
    var title=$("#titlearea").val();
    var unit=$("#float_unit_input").val();
    var trend=$("#float_trend input[name='float_trend_radio']:checked").val();
    if(name == '' || name === undefined ) {
        alert_info_not_all();
            return;
    }
    switch (op){
        case operations.create:
            dataOperator.insert(name, type,title,unit,trend,row);
            break;
        case operations.edit:
            dataOperator.edit(name,title,unit,trend,row);
            break;
    }
}
//用于存储XYZ的信息
function create3MatrixField(fid,xName,xTitle,yName,yTitle,zName){
    var data={fid:fid,xName:xName,xTitle:xTitle,yName:yName,yTitle:yTitle,zName:zName};
    $.get(fieldUrl.create3Matrix,data,
    function(result){
        if(!result.successful){
            $.messager.show({title: '操作结果', msg: "XYZ维度信息不正确"});
            return;
        }
    });
}

dataOperator = {
    tree:$("#database_data"),
    insert:function(name,type,title,unit,trend,row){
        var node=$('#database_data').treegrid('getSelected');
        var pid;
        if(node==null){
            pid = 0;//创建根节点
        } else{
            pid = node.id;
        }
        var data={name:name, type:type,schemaId:params()['databaseId'], parentId:pid};
        if(type==fieldMatrix){
            data.remark3=title;
        }else if(type==fieldFloat){
            data.remark3=unit;
            data.remark1=trend;
        }
        $.get(fieldUrl.create,data,function(result){
            if(result.successful) {
                $('#databaseData_dialog').dialog('close');
                var nodeData = {id: result.data, text: data.name, parentId: pid};
                switch (type){
                    case fieldCatalogType:
                        nodeData.attributes=fieldCatalogName;
                        nodeData.iconCls=fieldCatalogIcon;break;
                    case fieldFloat:
                        nodeData.attributes=fieldFloatName;
                        nodeData.iconCls=fieldFloatIcon;break;
                    case fieldText:
                        nodeData.attributes=fieldTextName;
                        nodeData.iconCls=fieldTextIcon;break;
                    case fieldPicture:
                        nodeData.attributes=fieldPictureName;
                        nodeData.iconCls=fieldPictureIcon;break;
                    case fieldAttach:
                        nodeData.attributes=fieldAttachName;
                        nodeData.iconCls=fieldAttachIcon;break;
                    case fieldMatrix:
                        nodeData.attributes=fieldMatrixName;
                        nodeData.iconCls=fieldMatrixIcon;break;
                    case fieldMulti:
                        nodeData.attributes=fieldMultiName;
                        nodeData.iconCls=fieldMultiIcon;break;
                    case field3D:
                        nodeData.attributes=field3DName;
                        nodeData.iconCls=field3DIcon;break;
                    case fieldLink:
                        nodeData.attributes=fieldLinkName;
                        nodeData.iconCls=fieldLinkIcon;break;
                    case fieldTime:
                        nodeData.attributes=fieldTimeName;
                        nodeData.iconCls=fieldTimeIcon;break;
                    case fieldVideo:
                        nodeData.attributes=fieldVideoName;
                        nodeData.iconCls=fieldVideoIcon;break;
                    case field3Matrix:
                        nodeData.attributes=field3MatrixName;
                        nodeData.iconCls=fieldDataIcon;break;
                    default :
                        nodeData.attributes=fieldFloatName;
                        nodeData.iconCls=fieldDataIcon;break;
                }
                $("#database_data").treegrid("append", {parent: node.id, data: [nodeData]});
                if(type==field3Matrix){
                        var xName=$("#3matrix_x_name").val();
                        var xTitle=$("#title_x").val();
                        var yName=$("#3matrix_y_name").val();
                        var yTitle=$("#title_y").val();
                        var zName=$("#3matrix_z_name").val();
                        create3MatrixField(nodeData.id,xName,xTitle,yName,yTitle,zName);
                }
            }
            $.messager.show({title: '操作结果', msg: result.message});
        });
    },
    edit:function(name,title,unit,trend,row){
        if(!row){
            alert_choose();
            return;
        }
        var id = row.id;
        var data={id:id, name:name};
        var type=row.attributes;
        if(type==fieldMatrixName.trim()){
            data.remark3=title;
        }else if(type==fieldFloatName.trim()){
            data.remark3=unit;
            data.remark1=trend;
        }else if(type==field3Matrix){

        }
        $.get(fieldUrl.edit, data,
            function (result) {
                if(result.successful){
                    $('#databaseData_dialog').dialog('close');
                    $("#database_data").treegrid("updateRow",{index:row.id,row:{text:name}})
                }
                $.messager.show({title: '操作结果', msg: result.message});
            });
    },
    remove:function(){
        var row = $('#database_data').treegrid('getSelected');
        var id = row.id;
        $.get(fieldUrl.destroy, {id:id},function(result){
            if(result.successful) {
                $("#database_data").treegrid("remove", row.id);
                clearSelection();
            }
            $.messager.show({title: '操作结果', msg:result.message});
        });
    }
};


function outputFieldData(){
    var row = $('#database_data').treegrid('getSelected');
    var fieldId;
    if(row==null){
        fieldId=1;
    }else{
        fieldId=row.id;
    }
    window.open(fieldUrl.downloadData+"?schemaId="+params()['databaseId']+"&fieldId="+fieldId);
}

function clearSelection(){
    delete params()['dataSelected'];
}

function upNode(){
    var row = $('#database_data').treegrid('getSelected');
    if(row==null){
        alert_choose();
        return;
    }
    if(row.id==1){
        alert_not_move();
        return;
    }
    var selectRow=$('tr[id*=datagrid-row-r]').filter("[id$="+row.id+"]");
    var pre=selectRow.prev();
    var preId=pre.attr("node-id");
    if(preId==1|| pre.size()==0){
        alert_not_move();
        return;
    }
    $.post(fieldUrl.moveNode,{frontNodeId:preId,backNodeId:row.id},function(result){
            if(result.successful){
                var node=$('#database_data').treegrid('pop',row.id);
                $('#database_data').treegrid('insert',{before:preId,data:node});
                $('#database_data').treegrid('select',row.id);
            }else{
                alert_not_move();
            }
        });
}

function downNode(){
    var row = $('#database_data').treegrid('getSelected');
    if(row==null){
        alert_choose();
        return;
    }
    if(row.id==1){
        alert_not_move();
        return;
    }
    var selectRow=$('tr[id*=datagrid-row-r]').filter("[id$="+row.id+"]");
    var nextNode=selectRow.next();
    var nextId=nextNode.attr("node-id");
    if(nextNode.size()==0){
        alert_not_move();
        return;
    }
    $.post(fieldUrl.moveNode,{frontNodeId:row.id,backNodeId:nextId},function(result){
        if(result.successful){
            var node=$('#database_data').treegrid('pop',nextId);
            $('#database_data').treegrid('insert',{before:row.id,data:node});
            $('#database_data').treegrid('select',row.id);
        }else{
            alert_not_move();
        }
    });
}

function setDatabase(){
    var nodeId=params()['databaseId'];
    $.get(fieldUrl.setDatabase,{id:nodeId},
        function(result){
            $.messager.show({title: '操作结果', msg: result.message});
        });
}

function infoSave(){
    var content=$("#info_area").val();
    $.post(schemaUrl.setSchemaRemark3,{id:params()['databaseId'],remark3:content},function(result){
        $.messager.show({title: '操作结果', msg:result.message});
    });
}


//choose node tip
function alert_choose(){
    $.messager.alert("\""+operateTip+"\"","\""+chooseNode+"\"","warning");
}
//choose a node which is not leaf
function alert_no_leaf(){
    $.messager.alert("\""+operateTip+"\"","\""+notLeaf+"\"","warning");
}
//user need to complete all the information
function alert_info_not_all(){
    $.messager.alert("\""+operateTip+"\"","\""+infoNotAll+"\"","warning");
}

//can not move the node
function alert_not_move(){
    $.messager.alert("\""+operateTip+"\"","\""+notMove+"\"","warning");
}